package com.jy.rhin.support.util;

import com.jy.rhin.infra.exception.RhinAggrErrorType;
import com.jy.rhin.infra.exception.RhinAggrException;
import org.springframework.util.FastByteArrayOutputStream;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import java.io.StringReader;

/**
 * @Description:
 * @Author: lww
 * @Date: 2022/7/15 11:48
 */
public class XmlUtils {

    private XmlUtils() {
    }

    /**
     * 对象转成xmlString
     *
     * @param object
     * @return
     */
    public static String objToXmlString(Object object) {
        try {
            JAXBContext jc = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = jc.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            FastByteArrayOutputStream os = new FastByteArrayOutputStream();
            marshaller.marshal(object, os);
            return os.toString();
        } catch (Exception e) {
            throw new RhinAggrException(RhinAggrErrorType.MESSAGE_XML_CONVERT_ERROR, e.getMessage());
        }

    }

    /**
     * xmlString转成对象
     *
     * @param xmlString xml字符串
     * @param tClass    转化的对象
     * @return T
     */
    public static <T> T xmlStringToObj(String xmlString, Class<T> tClass) {
        try {
            JAXBContext context = JAXBContext.newInstance(tClass);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            T obj = (T) unmarshaller.unmarshal(new StringReader(xmlString));
            return obj;
        } catch (JAXBException e) {
            throw new RhinAggrException(RhinAggrErrorType.MESSAGE_XML_CONVERT_ERROR, e.getMessage());
        }
    }
}
